/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cumulusCloud.repository.folderdb.converter.xml;

import java.io.InputStream;
import java.io.OutputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import cumulusCloud.common.ManageUser;
import cumulusCloud.common.objects.CloudSession;
import cumulusCloud.folderdb.converter.Converter;
import cumulusCloud.tools.XML;

public class ConverterCloudSessionXml implements Converter<CloudSession> {

	@Override
	public String getId(CloudSession object) {
		return object.token;
	}

	@Override
	public CloudSession toObject(InputStream in) {
		CloudSession result = new CloudSession();
		
		try {
			Document doc = XML.loadFromFile(in);
			Element rootElement = doc.getDocumentElement();
			
			String value = XML.getTextValue(rootElement, "token");
			if (value != null) {
				result.token = value;
			}
			value = XML.getTextValue(rootElement, "user");
			if (value != null) {
				result.user = ManageUser.getUser(value);
			}
			value = XML.getTextValue(rootElement, "expiration");
			if (value != null) {
				result.expiration = Long.valueOf(value);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		return result;
	}

	@Override
	public void toSerial(CloudSession object, OutputStream out) {
		try {
			Document doc = XML.createXmlDocument();

			Element sessionElement = doc.createElement("session");
			
			Element tokenElement = doc.createElement("token");
			tokenElement.appendChild(doc.createTextNode(object.token));
			Element userElement = doc.createElement("user");
			userElement.appendChild(doc.createTextNode(object.user.name));
			Element expirationElement = doc.createElement("expiration");
			expirationElement.appendChild(doc.createTextNode(Long.toString(object.expiration)));
			
			sessionElement.appendChild(tokenElement);
			sessionElement.appendChild(userElement);
			sessionElement.appendChild(expirationElement);
			
			doc.appendChild(sessionElement);

			XML.saveToFile(doc, out);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}


}
